<template>
	<div class="admin-home-page w-full flex flex-col items-center justify-center py-10">
		<el-card class="w-full max-w-md text-center">
			<div class="flex flex-col items-center">
				<el-avatar :size="80" :src="adminInfo.avatar || defaultAvatar" class="mb-2" />
				<div class="font-bold text-lg mb-1">欢迎你，{{ adminInfo.nickname }}</div>
				<div class="text-gray-500 text-sm mb-4">账号：{{ adminInfo.username }}</div>
				<div class="flex gap-2 justify-center">
					<el-button type="primary" @click="editDialogVisible = true">修改资料</el-button>
					<el-button type="warning" @click="pwdDialogVisible = true">修改密码</el-button>
				</div>
			</div>
		</el-card>

		<!-- 修改资料弹窗 -->
		<els-dialog v-model="editDialogVisible" title="修改资料">
			<el-form :model="editForm" label-width="60px" class="pt-2">
				<el-form-item label="昵称">
					<el-input v-model="editForm.nickname" placeholder="请输入昵称" />
				</el-form-item>
				<el-form-item label="头像">
					<div>
						<el-avatar :size="60" :src="editForm.avatar || defaultAvatar" />
						<div></div>
						<single-upload :handle-upload="handleAvatarUpload" accept="image/*" />
					</div>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="editDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitEdit">保存</el-button>
			</template>
		</els-dialog>

		<!-- 修改密码弹窗 -->
		<els-dialog v-model="pwdDialogVisible" title="修改密码">
			<el-form :model="pwdForm" label-width="80px" class="pt-2">
				<el-form-item label="原密码">
					<el-input v-model="pwdForm.oldPassword" type="password" placeholder="请输入原密码" />
				</el-form-item>
				<el-form-item label="新密码">
					<el-input v-model="pwdForm.newPassword" type="password" placeholder="请输入新密码" />
				</el-form-item>
				<el-form-item label="确认密码">
					<el-input
						v-model="pwdForm.confirmPassword"
						type="password"
						placeholder="请再次输入新密码" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="pwdDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitPwd">保存</el-button>
			</template>
		</els-dialog>
	</div>
</template>

<script name="AdminHomePage" lang="ts" setup>
import md5 from 'md5';
import { ElMessage } from 'element-plus';
import ElsDialog from '~/components/ElsDialog/index.vue';
import SingleUpload from '~/components/UploadCom/SingleUpload/index.vue';

const defaultAvatar = '/favicon.ico';
const adminInfo = reactive({ _id: '', username: '', nickname: '', avatar: '' });
const editDialogVisible = ref(false);
const pwdDialogVisible = ref(false);
const editForm = reactive({ nickname: '', avatar: '' });
const pwdForm = reactive({ oldPassword: '', newPassword: '', confirmPassword: '' });

// 获取管理员信息
const fetchAdminInfo = async () => {
	const res = await $fetch('/api/admin/user/info');
	if (res.code === 1) {
		Object.assign(adminInfo, res.data);
		editForm.nickname = res.data.nickname;
		editForm.avatar = res.data.avatar;
	} else {
		ElMessage.error(res.message || '获取信息失败');
	}
};

onMounted(fetchAdminInfo);

// 头像上传回调
const handleAvatarUpload = async (file: File) => {
	const formData = new FormData();
	formData.append('files', file);
	const res = await fetch('/api/admin/file/upload', {
		method: 'POST',
		body: formData,
	}).then((r) => r.json());
	if (res.code === 1 && res.data && res.data[0]?.url) {
		editForm.avatar = res.data[0].url;
		ElMessage.success('头像上传成功');
	} else {
		ElMessage.error(res.message || '头像上传失败');
	}
};

// 提交资料修改
const submitEdit = async () => {
	const res = await $fetch('/api/admin/user/update', {
		method: 'PATCH',
		body: { _id: adminInfo._id, nickname: editForm.nickname, avatar: editForm.avatar },
	});
	if (res.code === 1) {
		ElMessage.success('资料修改成功');
		editDialogVisible.value = false;
		fetchAdminInfo();
	} else {
		ElMessage.error(res.message || '资料修改失败');
	}
};

// 提交密码修改
const submitPwd = async () => {
	if (!pwdForm.oldPassword || !pwdForm.newPassword || !pwdForm.confirmPassword) {
		ElMessage.warning('请填写完整');
		return;
	}
	if (pwdForm.newPassword !== pwdForm.confirmPassword) {
		ElMessage.warning('两次新密码不一致');
		return;
	}
	const res = await $fetch('/api/admin/user/updatePassword', {
		method: 'PATCH',
		body: {
			_id: adminInfo._id,
			oldPassword: md5(pwdForm.oldPassword),
			newPassword: md5(pwdForm.newPassword),
		},
	});
	if (res.code === 1) {
		ElMessage.success('密码修改成功');
		pwdDialogVisible.value = false;
		pwdForm.oldPassword = pwdForm.newPassword = pwdForm.confirmPassword = '';
	} else {
		ElMessage.error(res.message || '密码修改失败');
	}
};
</script>

<style lang="scss" scoped>
.admin-home-page {
	min-height: 60vh;
}
</style>
